import React from "react";
import ProTable from "@ant-design/pro-table";
import { useState, useRef, useImperativeHandle } from 'react';
import { getTaskList } from "../service";
import { useRequest, useIntl, FormattedMessage } from 'umi';
import _ from "lodash";


const TaskList = React.forwardRef((props, ref) => {
  const actionRef = useRef([]);
  const [listData, SetListData] = useState([])
  const intl = useIntl();

  const { loading, error, refresh } = useRequest(getTaskList, {
    defaultParams: { service_name: props.serviceName },
    onSuccess: (result, params) => {
      SetListData(result)
    },
  });

  useImperativeHandle(ref, () => ({
    refresh: refresh
  }));

  let columns = [
    {
      title: <FormattedMessage id="pages.diagnose.diagnosticID" defaultMessage="Diagnostic ID" />,
      dataIndex: "task_id",
      valueType: "textarea",
      sorter: (a, b) => (a.task_id.localeCompare(b.task_id))
    },
    {
      title: <FormattedMessage id="pages.diagnose.creationtime" defaultMessage="Creation time" />,
      dataIndex: "created_at",
      valueType: "dateTime",
      sorter: (a, b) => (Date.parse(a.created_at) - Date.parse(b.created_at))
    },
    {
      title: <FormattedMessage id="pages.diagnose.state" defaultMessage="State" />,
      dataIndex: 'status',
      width: 150,
      valueEnum: {
        Running: { text: <FormattedMessage id="pages.hostTable.status.running" defaultMessage="Running" />, status: 'Processing' },
        Success: { text: <FormattedMessage id="pages.diagnose.completediagnosis" defaultMessage="Complete diagnosis" />, status: 'Success' },
        Fail: { text: <FormattedMessage id="pages.diagnose.anomaly" defaultMessage="Anomaly" />, status: 'Error' },
      },
      sorter: (a, b) => (a.status.localeCompare(b.status))
    },
    {
      title: <FormattedMessage id="pages.diagnose.operation" defaultMessage="Operation" />,
      dataIndex: "option",
      valueType: "option",
      render: (_, record) => {
        if (record.status == "Success") {
          return (
            <a key="showMemInfo" onClick={() => {
              props?.onClick?.(record)
            }}><FormattedMessage id="pages.diagnose.viewdiagnosisresults" defaultMessage="Viewing diagnosis results" /></a>
          )
        }
        else if (record.status == "Fail") {
          return (
            <a key="showMemError" onClick={() => {
              props?.onError?.(record)
            }}><FormattedMessage id="pages.diagnose.viewerrormessages" defaultMessage="Viewing error messages" /></a>
          )
        }
        else {
          return (<span><FormattedMessage id="pages.diagnose.nooperation" defaultMessage="No operation is available for the time being" /></span>);
        }
      },
    }
  ];

  const FixField = ["created_at", "created_by", "id", "params", "service_name", "status", "task_id"]
  if (listData[0]) {
    let optionField = Object.keys(listData[0]).filter(i => !FixField.includes(i))
      .map(i => {
        let isNumber = typeof (listData[0][i]) === 'number'
        let isString = typeof (listData[0][i]) == 'string'
        let column = {
          title: i, dataIndex: i, valueType: "textarea"
        }
        if (isNumber) {
          return {
            ...column,
            sorter: (a, b) => {
              if (a[i] === undefined) {
                return -1
              } else if (b[i] === undefined) {
                return 1;
              } else {
                return Number(a[i]) - Number(b[i])
              }
            }
          }
        } else if (isString) {
          return {
            ...column,
            sorter: (a, b) => {
              if (a[i] === undefined) {
                return -1
              } else if (b[i] === undefined) {
                return 1;
              } else {
                return String(a[i]).localeCompare(String(b[i]));
              }
            }
          }
        } else {
          return column
        }
      })
    columns = optionField.concat(columns)
  }

  return (
    <ProTable
      options={{ reload: refresh }}
      loading={loading}
      rowKey="id"
      headerTitle={props.headerTitle || <FormattedMessage id="pages.diagnose.viewdiagnosticrecord" defaultMessage="Diagnostic record viewing" />}
      actionRef={ref}
      dataSource={listData}
      columns={columns}
      pagination={props.pagination || { pageSize: 5 }}
      search={props.search || false}
    />
  );
});

export default TaskList;
